<template>
  <TaskChatDialog
    :title="dialogTitle"
    :model-value="props.visible"
    width="68%"
    @open="open"
    @close="handleClose"
    destroy-on-close
    append-to-body
    :fullscreen="isFullScreen"
    :close-on-click-modal="false">
    <el-form :model="taskForm" label-width="125px" ref="ruleFormRef" :rules="taskFormRules" class="add-task-form">
      <div class="more-form">
        <el-row>
          <el-col :span="20">
            <el-form-item label="标题：" prop="taskTitle">
              <el-input
                class="title-input"
                v-model.trim="taskForm.taskTitle"
                placeholder="请输入任务标题"
                maxlength="15"
                show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="任务描述：">
              <Editor
                :defaultConfig="editorProps.defaultConfig"
                ref="editorRef"
                height="260px"
                :folderId="editorProps.folderId"
                :folderName="'任务'"
                :folderType="'task'"
                :valueHtml="taskForm.taskDetail"
                @fullScreenFlag="
                  (val) => {
                    isFullScreen = val
                  }
                "></Editor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="优先级：" prop="taskPriority">
              <SelectPriority
                v-model="taskForm.taskPriority"
                :listData="dict.dictMap['task_priority']"></SelectPriority>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务类型：" prop="taskProp">
              <SelectTask v-model="taskForm.taskProp" :listData="dict.dictMap['task_type']"></SelectTask>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件：">
              <el-upload
                :file-list="fileList"
                class="upload-demo"
                :accept="uploadAccept()"
                multiple
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                :on-change="onChange"
                :auto-upload="false">
                <el-button size="large" class="upload-btn">
                  <img src="@/assets/image/task/upload-icon.png" alt="" />
                  点击上传附件
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="关联人：" class="relate-person">
              <div class="relate-person-item">
                <span>指派人</span>
                <SelectUser
                  only
                  :userList="projectMemberList"
                  :defaultSelectUserList="defaultUserIdList"
                  @select="getExecute"></SelectUser>
              </div>
              <div class="relate-person-item">
                <span>协助人</span>
                <SelectUser
                  only
                  :userList="projectMemberList"
                  :defaultSelectUserList="defaultFollowUserIdList"
                  @select="getTrack"></SelectUser>
              </div>
              <div class="relate-person-item">
                <span>管理人</span>
                <SelectUser
                  only
                  :userList="projectMemberList"
                  :defaultSelectUserList="defaultTestUserIdList"
                  @select="getTest"></SelectUser>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划开始时间：" prop="planBegintime">
              <el-input
                ref="startTimeRef"
                v-model="taskForm.planBegintime"
                @focus="handleCalendarTime('start')"
                placeholder="请选择开始时间"
                :suffix-icon="Calendar" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划结束时间：" prop="planEndtime">
              <el-input
                ref="endTimeRef"
                v-model="taskForm.planEndtime"
                placeholder="请选择结束时间"
                :suffix-icon="Calendar"
                @focus="handleCalendarTime('end')" />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="total-time">
            * 合计任务用时{{ taskForm.planCostHour }}
            小时
          </el-col>
        </el-row>

        <el-card class="form-child-item" v-if="!isChildren && !taskForm.parentTaskId" style="display: none">
          <div class="child-item-title">子任务</div>
          <div class="child-item" v-for="(item, index) in taskForm.children" :key="index" @click="childItemClick(item)">
            <div class="child-item-num" v-if="item.taskCode">#{{ item.taskCode }}</div>
            <div class="child-item-system">
              <span>{{ item.taskTitle }}</span>
              <span v-show="item.taskUserName">指派给：{{ item.taskUserName }}</span>
            </div>
            <div class="child-item-date">
              {{
                `${dayjs(item.planBegintime).format('YYYY-MM-DD')} - ${dayjs(item.planEndtime).format('YYYY-MM-DD')}`
              }}
            </div>
            <div class="child-item-button">
              <el-button link type="danger" @click.stop="deleteChild(item)">删除</el-button>
            </div>
          </div>
          <div class="child-item-add" @click="addChildTask">+添加子任务</div>
        </el-card>
        <el-form-item label="周期设置：" style="display: none">
          <el-radio-group v-model="taskForm.taskCycleName" @change="taskCycleNameChange">
            <el-radio-button v-for="(item, index) in croneList" :key="index" :value="item.label">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="taskForm.taskCycleName === '自定义'"
          label="自定义："
          class="customize"
          style="display: none">
          <template #label>
            <span>自定义：</span>
            <el-tooltip placement="top">
              <el-icon>
                <QuestionFilled />
              </el-icon>
              <template #content>
                <div v-html="tip"></div>
              </template>
            </el-tooltip>
          </template>
          <div class="cron">
            <el-form-item
              v-for="(item, index) in taskCyleList"
              :key="index"
              label-width="5px"
              label=" "
              class="cron-content"
              :required="item.required"
              :error="item.error">
              <el-input
                v-model.trim="item.value"
                :placeholder="item.placeholder"
                maxlength="125"
                @input="changeValue(item)"
                @blur="checkCustomValid(item)"></el-input>
            </el-form-item>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submit">保存</el-button>
      </span>
    </template>
    <AddTask
      ref="addChildTaskRef"
      v-model:visible="childVisible"
      :append-to-body="true"
      :item-id="props.itemId"
      :project-id="props.projectId"
      :parent-data="parentChildData"
      isChildren
      :addTaskType="addChildTaskType"
      :parent-plan-begintime="taskForm?.planBegintime"
      :parent-plan-endtime="taskForm?.planEndtime"
      @addTaskChild="handleAddChild"></AddTask>
    <TaskChatDialog
      v-model="dialogVisible"
      width="70%"
      class="task-dialog"
      :title="taskDialogTitle"
      body-class-name="dialog-child-custom"
      @close="handleDetailClose"
      destroy-on-close
      append-to-body>
      <TaskDetail
        :task="taskData"
        :show-message="showMessage"
        allow-operations
        @refresh="getDetail"
        @receiveTask="handleReceiveTask"></TaskDetail>
    </TaskChatDialog>
    <!-- 日历弹窗 -->
    <TaskChatDialog
      v-model="dialogCalendarVisible"
      width="80%"
      class="task-dialog calendar-dialog"
      body-class-name="dialog-child-custom"
      @close="handleCalendarClose"
      destroy-on-close
      fullscreen
      append-to-body>
      <TaskCalendar :calendarData="taskInfo" />
    </TaskChatDialog>
  </TaskChatDialog>
</template>

<script setup>
import { QuestionFilled, Calendar } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useDictionary } from '@/use/use-dictionary'
import { addTaskInfo, updateTask, getTaskDetail, deleteTcTask } from '@/assets/api/task'
import { getProjectMember } from '@/assets/api/project'
import { uploadFile, downloadFile } from '@/assets/api/document'
import { ElMessage } from 'element-plus'
import Editor from '@/components/Editor'
import TaskDetail from '@/views/task/components/TaskDetail'
import useProject from '@/store/project'
import { uploadAccept } from '@/utils/task-utils'
import useEventBus from '@/use/use-event-bus.js'

const eventBus = useEventBus()

defineExpose({
  setTaskForm,
  stopLoading,
})

const projectStore = useProject()

const props = defineProps({
  visible: Boolean,
  itemId: [Number, String],
  projectId: [Number, String],
  taskId: [Number, String],
  isChildren: Boolean,
  parentPlanBegintime: [Number, String],
  parentPlanEndtime: [Number, String],
  parentData: Object,
  addTaskType: {
    type: String,
    default: 'add',
  },
})

const isFullScreen = ref(false)

const emit = defineEmits(['close', 'submitFinish', 'update:visible', 'addTaskChild'])

const dict = useDictionary(['task_priority', 'work_time', 'task_type'])

const childVisible = ref()

const tip = ref(
  "? , 要使用英文符号<br/>日：允许值：1-31 允许通配符：, - * / L W <br/>月：允许值：1-12 允许通配符：, - * / <br/>周：允许值：1-7 允许通配符： , - ? / L #<br/>* 表示所有值. 例如:日上设置'*',表示每天都会触发。<br/>? 表示不指定值 类似“*”<br/>- 表示区间。例如:在日上设置'10-12',表示每月10,11,12日都会触发。<br/>, 表示指定多个值，例如在周字段上设置 '1,3,5' 表示周一，周三和周五触发<br/>/ 用于递增触发。在月字段上设置'1/3'所示每月1号开始，每隔三天触发一次。<br/>L 表示最后的意思。在日字段设置上，表示当月的最后一天<br/>W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上设置'15W'，如果15号正好是周六，则找最近的周五(14号)触发<br/>小提示：'L'和 'W'可以一组合使用。如果在日字段上设置'LW',则表示在本月的最后一个工作日触发（一般指发工资）<br/># 序号(表示每月的第几个周几)，例如在周字段上设置'6#3'表示在每月的第三个周六.注意如果指定'6#5',正好第五周没有周六，则不会触发<br/>"
)
const uploadTip = ref('只能上传jpg/png/jpeg/pdf/doc/docx/xls/xlsx/mp4/avi文件')

const showAdvancedOptions = ref(true)

const datePickRef = ref()

const datePickerVisible = ref(false)

const todayStart = dayjs().startOf('day')

const todayEnd = dayjs().endOf('day')
const calendarValue = ref(new Date())

const ruleFormRef = ref()
const formatStr = 'YYYY-MM-DD'
const formatTime = 'HH:mm:ss'

const checkFlag = ref()

const dialogCalendarVisible = ref(false)

const taskCyleList = ref([
  {
    required: true,
    placeholder: '日',
    value: '',
    error: '',
  },
  {
    required: true,
    placeholder: '月',
    value: '',
    error: '',
  },
  {
    required: true,
    placeholder: '周',
    value: '',
    error: '',
  },
  // {
  //   required: false,
  //   placeholder: '年',
  //   value: '',
  //   error: '',
  // },
])
const taskForm = ref({})
const taskFormRules = {
  taskTitle: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  taskDetail: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
  taskPriority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  taskProp: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
  planBegintime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  planEndtime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  planCostHour: [{ required: true, message: '请输入计划消耗时间', trigger: 'blur' }],
}

const editorRef = ref()
const editorProps = reactive({
  defaultConfig: { placeholder: '请输入任务描述', readOnly: false, mode: 'default', maxLength: 256 },
  folderId: '',
  folderName: '',
})

const shortcuts = reactive([
  {
    text: '今天',
    value: () => {
      return [todayStart, todayEnd]
    },
  },
  {
    text: '明天',
    value: () => {
      return [todayStart, todayEnd.add(1, 'day')]
    },
  },
  {
    text: '3天',
    value: () => {
      return [todayStart, todayEnd.add(2, 'day')]
    },
  },
  {
    text: '5天',
    value: () => {
      return [todayStart, todayEnd.add(4, 'day')]
    },
  },
])

const chooseTimeType = ref(null)
const calendarTime = ref(null)

const taskInfo = ref({})
//使用computed 避免数据异步
provide(
  'taskInfo',
  computed(() => taskInfo.value)
)

const startTimeRef = ref()
const endTimeRef = ref()
function handleCalendarTime(type) {
  console.log('props.taskId', taskForm.value)
  console.log('props.parentData', props.parentData)
  taskInfo.value.start = props.parentData.itemBegin
  taskInfo.value.end = props.parentData.itemEnd
  taskInfo.value.taskUserId = taskForm.value.taskUserId
  taskInfo.value.taskUserName = taskForm.value.taskUserName
  taskInfo.value.taskId = taskForm.value.taskId
  chooseTimeType.value = type
  dialogCalendarVisible.value = true
}
eventBus.on('updateSelectDate', (data, type) => {
  const { planBegintime, planEndtime, planCostHour } = data
  // 新增
  if (type !== 'edit') {
    dialogCalendarVisible.value = false
    taskForm.value.planBegintime = planBegintime
    taskForm.value.planEndtime = planEndtime
    taskForm.value.planCostHour = planCostHour
  } else if (data.taskId === taskForm.value.taskId) {
    // 编辑本任务
    taskForm.value.planBegintime = planBegintime
    taskForm.value.planEndtime = planEndtime
    taskForm.value.planCostHour = planCostHour
  }
})
function getChooseTime() {
  if (chooseTimeType.value === 'start') {
    taskForm.value.planBegintime = calendarTime.value
  } else {
    taskForm.value.planEndtime = calendarTime.value
  }
  dialogCalendarVisible.value = false
}

watch(
  () => props.visible,
  (v) => {
    if (v) {
      resetTaskForm()
    }
  }
)

const croneList = [
  { label: '从不', value: null },
  { label: '每天', value: '0 0 0 * * ?' },
  // { label: '每个工作日', value: null },
  { label: '每周', value: '0 0 0 * * 1' },
  // { label: '每两周', value: '0 0 0 0/14 * ? *' },
  { label: '每月', value: '0 0 0 1 * ?' },
  { label: '每年', value: '0 0 0 1 1 ?' },
  { label: '自定义', value: null },
]

const dataTask = reactive({
  itemData: {},
  current: 0,
  tabCurrent: 0,
  fileList: [],
})
// 非表单字段校验
function checkCustomValid(item) {
  if (!item.value && item.required) {
    item.error = '字段不可为空'
    return false
  } else {
    item.error = ''
    return true
  }
}
function changeValue(item) {
  item.value = item.value.replace(/[\u4e00-\u9fa5]|\s+/g, '')
}
function planStartTimeChange(date) {
  taskForm.value.planBegintime =
    dayjs(date).startOf('day').format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.start)}`
  handlePlanCos()
}

function planEndTimeChange(date) {
  taskForm.value.planEndtime =
    dayjs(date).endOf('day').format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.end)}`
  handlePlanCos()
}

function planDateChange(date) {
  planStartTimeChange(date[0])
  planEndTimeChange(date[1])
}

function checkFlagChange(v) {
  switch (v) {
    case '1':
    case '3':
      taskForm.value.planBegintime =
        dayjs(taskForm.value.planBegintime).format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.start)}`
      break
    case '2':
    case '4':
      taskForm.value.planEndtime =
        dayjs(taskForm.value.planEndtime).format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.end)}`
      break
  }
  handlePlanCos()
}

function handlePlanCos() {
  const dayDiff = dayjs(taskForm.value.planEndtime).diff(dayjs(taskForm.value.planBegintime), 'day')
  const hourDiff = dayjs(taskForm.value.planEndtime).diff(dayjs(taskForm.value.planBegintime), 'hour')
  // taskForm.value.planCostDay = dayDiff + hourDiff >= Number(dict.getCode('work_time', '5')) ? 1 : 0.5
  if (dayDiff === 0) {
    taskForm.value.planCostDay = hourDiff >= Number(dict.getCode('work_time', '5')) ? 1 : 0.5
  } else if (dayDiff >= 1) {
    taskForm.value.planCostDay = dayDiff + 1
  }
  // taskForm.value.planCostDay = dayDiff + hourDiff >= Number(dict.getCode('work_time', '5')) ? dayDiff : 0.5
  taskForm.value.planCostHour = ''
}

function planCostDayChange(value) {
  if (value === 0.5) {
    if (checkFlag.value.start === '1') {
      checkFlag.value.end = '2'
    } else {
      checkFlag.value.end = '4'
    }
    taskForm.value.planEndtime =
      dayjs(taskForm.value.planBegintime).format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.end)}`
  } else {
    if (checkFlag.value.start === '1') {
      checkFlag.value.end = '4'
    }
    taskForm.value.planEndtime =
      dayjs(taskForm.value.planBegintime)
        .add(value - 1, 'day')
        .format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.end)}`
  }
}

const defaultUserIdList = ref([]) //默认/回显--指派给
const defaultFollowUserIdList = ref([]) //默认/回显--跟踪者
const defaultTestUserIdList = ref([]) //默认/回显--测试者
function setTaskForm(task) {
  let fileData = JSON.parse(task.taskAttach)
  if (Array.isArray(fileData)) {
    fileList.value = fileData.map((item) => {
      return {
        ...item,
        name: item.resourceName,
      }
    })
  } else if (fileData && Object.keys(fileData).length) {
    let file = {
      ...fileData,
      name: fileData.resourceName,
    }
    fileList.value.push(file)
  }
  checkFlag.value = {
    start: dict.translate('work_time', dayjs(task.planBegintime).format(formatTime)),
    end: dict.translate('work_time', dayjs(task.planEndtime).format(formatTime)),
  }
  if (task.taskCycleName === '自定义') {
    taskCyleList.value.forEach((item, index) => [(item.value = task.taskCycle.split(' ').slice(3)[index] || '')])
  }
  taskForm.value = task
  taskForm.value.taskPriority = String(task.taskPriority)
  taskForm.value.taskProp = String(task.taskProp)
  defaultUserIdList.value =
    task.taskUserId && task.taskUserId !== -1 ? [{ userId: task.taskUserId, userName: task.taskUserName }] : []
  defaultFollowUserIdList.value =
    task.taskAssistid && task.taskAssistid !== -1 ? [{ userId: task.taskAssistid, userName: task.taskAssistName }] : []
  defaultTestUserIdList.value =
    task.taskLeaderid && task.taskLeaderid !== -1 ? [{ userId: task.taskLeaderid, userName: task.taskLeaderName }] : []
}

function stopLoading(type) {
  loading.value = type === 'stop' ? false : true
}

function resetTaskForm() {
  planCostHourError.value = ''
  checkFlag.value = {
    start: '1',
    end: '4',
  }
  taskForm.value = {
    taskTitle: null,
    taskDetail: '',
    planCostDay: 1,
    planCostHour: 0,
    // planBegintime: todayStart.format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.start)}`,
    // planEndtime: todayEnd.format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.end)}`,
    planBegintime: '',
    planEndtime: '',
    taskPriority: '3',
    taskProp: '1',
    taskCycleName: '从不',
    taskCycle: '',
    children: [],
  }
  taskCyleList.value.forEach((item) => {
    item.value = ''
  })
  dialogTitle.value = props.addTaskType === 'edit' ? '编辑任务' : '添加任务'
  if (props.addTaskType === 'edit') {
    getDetail(props.taskId, 'refresh')
  }
  editorProps.folderId = projectStore.getProjectInfo.projectFolderId
  editorProps.folderName = projectStore.getProjectInfo.projectName
  getProjectMemberData()
}

function taskCycleNameChange(name) {
  taskForm.value.taskCycle = croneList.find((i) => i.label === name).value
}

function handleClose() {
  defaultUserIdList.value = [] //默认/回显--指派给
  defaultFollowUserIdList.value = [] //默认/回显--跟踪者
  defaultTestUserIdList.value = [] //默认/回显--测试者
  fileRaws = []
  fileList.value = []
  isFullScreen.value = false
  emit('close')
  emit('update:visible', false)
  setTimeout(() => {
    showAdvancedOptions.value = false
  }, 300)
}
async function handleReceiveTask(task) {
  task.currentStatus = 2
  const res = await updateTask(task)
  if (res.code === 200) {
    ElMessage.success('任务领取成功')
  } else {
    ElMessage.error(res.msg)
  }
}
function handleAddChild(child, fileData) {
  const needUploadList = fileFormate(fileData)
  addChildTaskRef.value.stopLoading()
  if (needUploadList.length) {
    handleUploadFile(needUploadList)
      .then((res) => {
        child.taskAttach = JSON.stringify(res.data)
        onAddChild(child)
      })
      .catch((err) => {
        addChildTaskRef.value.stopLoading('stop')
      })
  } else {
    onAddChild(child)
  }
}

function onAddChild(child) {
  if (taskForm.value.taskId) {
    child.parentTaskId = taskForm.value.taskId
    child.itemId = taskForm.value.itemId
    child.projectId = taskForm.value.projectId
    onSubmit(child, 'child')
  } else {
    child.itemId = props.itemId
    child.projectId = props.projectId
    taskForm.value.children.push(child)
    //
    setTimeout(() => {
      addChildTaskRef.value.stopLoading('stop')
    }, 1000)
  }
  childVisible.value = false
}
const parentChildData = ref({})
function addChildTask() {
  const data = JSON.parse(JSON.stringify(taskForm.value))
  parentChildData.value = { itemBegin: data.planBegintime, itemEnd: data.planEndtime }
  addChildTaskType.value = 'add'
  childVisible.value = true
}

const loading = ref(false)

const childId = ref(1)
function submit() {
  ruleFormRef.value.validate(async (valid) => {
    let otherValid = false
    if (taskForm.value.taskCycleName === '自定义') {
      // 校验自定义内容
      taskCyleList.value.forEach((item) => {
        if (item.required && checkCustomValid(item)) {
          otherValid = true
        }
      })
    } else {
      otherValid = true
    }
    if (valid && otherValid) {
      const form = JSON.parse(JSON.stringify(taskForm.value))
      if (form.taskCycleName === '自定义') {
        form.taskCycle =
          '0 0 0 ' +
          taskCyleList.value
            .map((item) => {
              return item.value
            })
            .join(' ')
      }
      // form.planBegintime =
      //   dayjs(form.planBegintime).format('YYYY-MM-DD') + ` ${dict.getCode('work_time', checkFlag.value.start)}`
      // form.planEndtime =
      //   dayjs(form.planEndtime).format('YYYY-MM-DD') + ` ${dict.getCode('work_time', checkFlag.value.end)}`
      form.taskDetail = editorRef.value.getHtml()
      if (props.isChildren) {
        form.childId = childId.value
        ++childId.value
        emit('addTaskChild', form, fileList.value)
      } else {
        const isAdd = !form.taskId
        if (isAdd) {
          form.itemId = props.itemId
          form.projectId = props.projectId
        }
        const needUploadList = fileFormate(fileList.value)
        if (needUploadList.length) {
          loading.value = true
          handleUploadFile(needUploadList)
            .then((res) => {
              form.taskAttach =
                props.addTaskType === 'add'
                  ? JSON.stringify(res.data)
                  : JSON.stringify([...res.data, ...fileFormate(fileList.value, 'object')])
              onSubmit(form, 'parent')
            })
            .catch((err) => {
              loading.value = false
            })
        } else {
          form.taskAttach = JSON.stringify(fileList.value)
          onSubmit(form, 'parent')
        }
      }
    }
  })
}

async function onSubmit(form, type) {
  const isAdd = !form.taskId

  type === 'parent' ? (loading.value = true) : addChildTaskRef.value.stopLoading()
  const res = await (isAdd ? addTaskInfo : updateTask)(form)
  if (res.code === 200) {
    ElMessage.success('提交成功')
    type === 'parent' ? handleClose() : getDetail(taskForm.value.taskId, 'refresh')
    emit('submitFinish')
  } else {
    ElMessage.error(res.msg)
  }
  type === 'parent' ? (loading.value = false) : addChildTaskRef.value.stopLoading('stop')
}
const addChildTaskType = ref('add')
const addChildTaskRef = ref()
// 编辑子项
function editChildTask(item) {
  const data = JSON.parse(JSON.stringify(item))
  addChildTaskRef.value.setTaskForm(data)
  addChildTaskType.value = 'edit'
  childVisible.value = true
}
// 删除子项
function deleteChild(child) {
  if (child.childId) {
    taskForm.value.children = taskForm.value.children.filter((item) => item.childId !== child.childId)
  } else if (child.taskId) {
    handleDeleteTask(child.taskId)
    emit('submitFinish')
    // emit('deleteTask', JSON.parse(JSON.stringify(child)))
  }
}

function handleDeleteTask(taskId) {
  deleteTcTask(taskId).then((res) => {
    if (res.code === 200) {
      getDetail(taskForm.value.taskId, 'refresh')
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 打开详细时间选择
function controlDatePicker() {
  datePickerVisible.value = !datePickerVisible.value
  datePickerVisible.value ? datePickRef.value.handleOpen() : datePickRef.value.handleClose()
}

// 高级选项
function openAdvancedOptions() {
  showAdvancedOptions.value = !showAdvancedOptions.value
}
function handleTab(index) {
  dataTask.tabCurrent = index
}

const projectMemberList = ref([])
function getProjectMemberData() {
  //查询项目成员
  getProjectMember({ projectId: props.projectId, effectFlag: 1 }).then((res) => {
    if (res.code === 200) {
      projectMemberList.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}

function getExecute(val) {
  taskForm.value.taskUserId = val.length > 0 ? val[0].userId : -1
  taskForm.value.taskUserName = val.length > 0 ? val[0].userName : -1
}
function getTrack(val) {
  taskForm.value.taskAssistid = val.length > 0 ? val[0].userId : -1
  taskForm.value.taskAssistName = val.length > 0 ? val[0].userName : -1
}
function getTest(val) {
  taskForm.value.taskLeaderid = val.length > 0 ? val[0].userId : -1
  taskForm.value.taskLeaderName = val.length > 0 ? val[0].userName : -1
}

// 打开子任务详情
const dialogVisible = ref(false)
const taskData = ref({})
const showMessage = ref(false)
function childItemClick(task) {
  if (task.taskId) {
    getDetail(task.taskId, 'viewInfo')
  }
}

async function getDetail(id, type) {
  getTaskDetail(id).then((res) => {
    if (res.code === 200) {
      if (type === 'viewInfo') {
        taskData.value = res.data
        dialogVisible.value = true
      } else if (type === 'refresh') {
        setTaskForm(res.data)
      }
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const taskDialogTitle = computed(() => {
  if (taskData.value.taskTitle) {
    const { projectName, itemName, taskTitle, taskCode } = taskData.value
    return `${projectName}/${itemName}/${taskTitle}-#${taskCode}`
  }
  return ''
})

function handleDetailClose() {
  showMessage.value = false
  taskData.value = {}
}

function handleCalendarClose() {
  console.log('startTimeRef.value', startTimeRef.value.blur())
  startTimeRef.value.blur()
  endTimeRef.value.blur()
  dialogCalendarVisible.value = false
}

const dialogTitle = ref('添加任务')
function open() {
  // taskForm.value.taskId ? (dialogTitle.value = '编辑任务') : (dialogTitle.value = '添加任务')
  // props.taskId ? (dialogTitle.value = '编辑任务') : (dialogTitle.value = '添加任务')
  // editorProps.folderId = projectStore.getProjectInfo.projectFolderId
  // editorProps.folderName = projectStore.getProjectInfo.projectName
  // getProjectMemberData()
  // if (props.taskId) {
  //   getDetail(props.taskId, 'refresh')
  // }
}

// 文件列表移除文件时的钩子
function handleRemove(file) {
  fileList.value = fileList.value.filter((obj) => {
    if (file.raw?.uid) {
      return obj.uid !== file.raw.uid
    } else {
      return obj.resourceId !== file.resourceId
    }
  })
}

// 上传文件之前的钩子
function beforeUpload(file) {}

// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
function onChange(file) {
  // fileRaws.push(file.raw)
  fileList.value.push(file)
}

function handlePreview(file) {
  downloadFile(file.resourceId).then((res) => {
    let mimeType = file.mimeType
    let type = mimeType ? mimeType : 'application/zip'
    let blob = new Blob([res], { type: type })
    let url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${file.resourceName}`
    link.click()
    URL.revokeObjectURL(url)
  })
}

// 文件上传
const fileList = ref([])
let fileRaws = []
function handleUploadFile(data) {
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    formData.append('folderParentId', projectStore.getProjectInfo.projectFolderId)
    formData.append('relativePath', '任务')
    formData.append('type', 'task')
    data.forEach((file) => {
      formData.append('files', file.raw)
    })
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        resolve(res)
      } else {
        reject(res)
      }
    })
  })
}

function fileFormate(data, type = 'file') {
  let res = []
  if (Array.isArray(data)) {
    res = data.filter((item) => {
      if (type === 'file') {
        return item.raw
      } else {
        return !item.raw
      }
    })
  }

  return res
}

let planCostHourError = ref('')

// 输入数字校验
function onInput(val) {
  const dayDiff = dayjs(taskForm.value.planEndtime).diff(dayjs(taskForm.value.planBegintime), 'day')
  let maxHours = 0
  dayDiff === 0
    ? (maxHours = Number(dict.getCode('work_time', '5')))
    : (maxHours = (dayDiff + 1) * Number(dict.getCode('work_time', '5')))

  let num = val.replace(/[^\d]/g, '')
  if (num < 1) {
    taskForm.value.planCostHour = 1
    planCostHourError.value = '最小值不可小于1'
  } else if (num > maxHours) {
    taskForm.value.planCostHour = maxHours
    planCostHourError.value = `最大值不可大于${maxHours}`
  } else {
    planCostHourError.value = ''
  }
}

function onLimit() {
  if (!taskForm.value.currentStatus || taskForm.value.currentStatus === 1) {
    return false
  } else {
    return true
  }
}
</script>

<style lang="scss" scoped>
.add-task-form {
  .task-consume-time {
    @include use-flex(center, center);
    .date-picker {
      @include use-flex(center, center);
      cursor: pointer;
      position: relative;
      margin: 0 10px;
      :deep(.elp-date-editor) {
        &.date-picker-wrap {
          visibility: hidden;
          position: absolute;
          left: 50%;
          bottom: 0;
          height: 0;
          width: 0;
          padding: 0;
        }
      }
    }
    .advanced-options {
      margin-left: auto;
    }
  }
  .more-form {
    padding-top: 20px;
    .relate-person {
      &-item {
        display: flex;
        align-items: center;
        margin-right: 40px;
        line-height: 1px;
        color: var(--elp-text-color-regular);
        span {
          margin-right: 5px;
        }
      }
    }
    .upload-btn {
      img {
        margin-right: 5px;
        width: 14px;
        height: 14px;
      }
      font-size: 14px;
      color: var(--elp-text-color-regular);
    }
    .total-time {
      color: var(--elp-text-color-regular);
      line-height: 34px;
      font-size: 14px;
      padding-left: 10px;
    }
    .form-child-item {
      margin-bottom: 18px;
      .child-item-title {
        font-weight: bold;
        margin-bottom: 10px;
      }
      .child-item {
        @include use-flex(center, normal, row);
        padding: 13px;
        margin-bottom: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        cursor: pointer;
        .child-item-num {
          color: #299afc;
        }
        .child-item-system {
          cursor: pointer;
          font-weight: bold;
          margin: 0 10px;
          span {
            margin-right: 5px;
          }
        }
        .child-item-date {
          color: #999999;
          margin: 0 5px;
        }
        .child-item-name {
          @include use-flex(normal, normal, row);
          margin: 0 5px;
        }

        &-button {
          margin-left: auto;
        }
      }
      .child-item-add {
        height: 40px;
        line-height: 40px;
        text-align: center;
        cursor: pointer;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
      }
    }
  }
}

:deep(.title-input .elp-input__inner) {
  font-weight: 700 !important;
}
.cron {
  display: flex;
  align-items: center;
  &-content {
    &:not(:first-child) {
      margin-left: 15px;
    }
    width: 100%;
    :deep(.elp-form-item__label) {
      padding: 0;
    }
    :deep(.elp-form-item__content) {
      flex-wrap: nowrap;
    }
    .elp-input {
      margin-left: 5px;
    }
  }
}
.customize {
  :deep(.elp-form-item__label) {
    display: flex;
    align-items: center;
  }
}

.planCostHour {
  width: 350px;
}

:deep(input)::-webkit-outer-spin-button,
:deep(input)::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
:deep(input[type='number']) {
  -moz-appearance: textfield !important;
}
</style>
